var React = require("react");
var ReactDOM = require("react-dom");
import {Link, hashHistory} from 'react-router';
class HeadTitleComponent extends React.Component {

  handleClick(e) {
    this.props.handleBack(this.props.title);
  }

  render() {
    return (
      <div className="fruit-header">
        <a onClick={this.handleClick.bind(this)} className='leftBtn'>&nbsp;</a>
        <span>{this.props.title}</span>
      </div>
    )
  }
}

define('FruitSelectionPage',function(){
var _FruitSelectionPage = React.createClass ({
    inputDelay:null,    //指示是否有一个延迟timer启动，延迟过后向服务发起请求，减少用户快速输入时，服务器负担
    xhr:null,           //记录已发起的请求，如果请求没结束，放弃之
    getDefaultProps:function(){
        input:null
    },
    //getValue:function(){    //返回输入的果品
    //    if(this.state.selectedFruit == null){
    //        return {//手工输入的果品，没有Code
    //            name:this.refs.inputedFruit.value,
    //            code:null
    //        }
    //    }
    //    return this.state.selectedFruit;
    //},
    getInitialState:function(){
            return {
                selectedFruit:null,
                hidden:true,
                showCateList:true,
                showLevelOne:false,
                showKeyList:false,
                title:'发布水果',
                value:'请输入水果关键词',
                goodsCode:'',
                cateFruits:[],
                candidateFruits:[],
                LevelOneFruits:[],
                LevelTwoFruits:[],
                fruitsItemList:''
            };
    },
    componentDidMount:function(){
      var jsonp_url = "http://203.195.176.188:9002/pgsearch/ctmtype.php?data=l1";
      var myself = this;
      if(this.xhr != null && this.xhr.readyState != 4) this.xhr.abort();
      //this.xhr = $.getJSON(jsonp_url + val + "*&callback=?",null,
      this.xhr = $.getJSON(jsonp_url,null,
        function(data){
          myself.setState({
            showCateList:true,
            showLevelOne:false,
            showKeyList:false,
            title:'发布水果',
            value:'请输入水果关键词',
            cateFruits:data,
            selectedFruit:null,
            hidden:false});
        }
      ).fail(function(){
          if(this.state.cateFruits != null || this.state.selectedFruit != null ){
            myself.setState({cateFruits:null,selectedFruit:null,hidden:false});
          }
        });
      return true;
    },
    handleLeaveInput:function(e){
      console.info('blur');

    },
    handleFocus:function(e){
        this.setState({
          showCateList:false,
          showLevelOne:false,
          showKeyList:true,
          cateFruits:[],
          candidateFruits:[],
          LevelOneFruits:[],
          LevelTwoFruits:[],
          fruitsItemList:'',
          value:''
        });
    },
    handleFruitInput:function(e){
        if(this.inputDelay != null) clearTimeout(this.inputDelay);
        var value = e.target.value;
        this.setState({
          value:value
        });
        var myself = this;
        if(this.state.selectedFruit != null && e.target.value != this.state.selectedFruit.name){//刚选择的内容被更改了
          this.state.selectedFruit = null;//不应该这样操作，但从当前情况看，没有必要重新刷新，这样也有意义，为了语义的完整性
        }
        this.inputDelay = setTimeout(function(){
                        myself.proposeFruit(value);
                    },200);
    },
    proposeFruit:function(val){
        var jsonp_url = "http://203.195.176.188:9002/pgsearch/pgsearch.php?data=md_goods&format=json&str=*";
        var myself = this;
        if(val.length > 1){
            if(this.xhr != null && this.xhr.readyState != 4) this.xhr.abort();
                this.xhr = $.getJSON(jsonp_url + val + "*&callback=?",null,
                    function(data){
                        myself.setState({candidateFruits:data,selectedFruit:null,hidden:false});
                    }
                ).fail(function(){
                    if(this.state.candidateFruits != null || this.state.selectedFruit != null ){
                        myself.setState({candidateFruits:null,selectedFruit:null,hidden:false});
                    }
                });
            return true;
        }else{
            this.setState({candidateFruits:[],hidden:false});
        }
        return false;
    },
    //handleTipsClick(e){
    //    this.refs.inputedFruit.value = e.target.textContent;
    //    this.setState({
    //        selectedFruit:{
    //                name:e.target.textContent,
    //                code:e.target.id
    //            },
    //        candidateFruits:[]
    //    });
    //},
  changeTitle(title){
    this.setState({
      title:title
    });
  },
  selCateItem(e){
    this.changeTitle(e.target.innerHTML);
    this.getLevelOneFruits(e.target.id);
    this.setState({
      title:e.target.innerHTML,
      showCateList:false,
      showLevelOne:true
    });
  },
  selLevelOne(e){
    if(e.target.nodeName!='LI')return;
    //展开改类之前首先关闭其它类别
    var allLiNodes = document.getElementById('levelOne').getElementsByTagName('li');
    if(allLiNodes && allLiNodes.length>0){
      for(var i=0,len=allLiNodes.length;i<len;i++){
        if(allLiNodes[i].className && allLiNodes[i].className=='change-item'){
          allLiNodes[i].classList.remove('change-item');
        };
      }
    };
    var liNode = e.target;
    liNode.classList.add('change-item');
    this.getLevelTwoFruits(e.target.id,liNode,liNode.innerHTML);

  },
  getLevelOneFruits(code){ //获取某个一级分类下的所有二级分类
    var jsonp_url = "http://203.195.176.188:9002/pgsearch/ctmtype.php?data=l2&l1node="+code;
    var myself = this;
    if(this.xhr != null && this.xhr.readyState != 4) this.xhr.abort();
    //this.xhr = $.getJSON(jsonp_url + val + "*&callback=?",null,
    this.xhr = $.getJSON(jsonp_url,null,
      function(data){
        myself.setState({LevelOneFruits:data,selectedFruit:null,hidden:false});
      }
    ).fail(function(){
        if(this.state.LevelOneFruits != null || this.state.selectedFruit != null ){
          myself.setState({LevelOneFruits:null,selectedFruit:null,hidden:false});
        }
      });
    return true;
  },
  getLevelTwoFruits(code,node,html){ //获取某个二级分类下的所有单品
    var showLevelTwoFruits = this.showLevelTwoFruits;
    var getFruitsItemList = this.getFruitsItemList;
    var jsonp_url = "http://203.195.176.188:9002/pgsearch/ctmtype.php?data=items&l2node="+code;
    var myself = this;
    if(this.xhr != null && this.xhr.readyState != 4) this.xhr.abort();
    //this.xhr = $.getJSON(jsonp_url + val + "*&callback=?",null,
    this.xhr = $.getJSON(jsonp_url,null,
      function(data){
        myself.setState({LevelTwoFruits:data,fruitsItemList:showLevelTwoFruits(data),selectedFruit:null,hidden:false});
        getFruitsItemList(node,html);

      }
    ).fail(function(){
        if(this.state.LevelTwoFruits != null || this.state.selectedFruit != null ){
          myself.setState({LevelTwoFruits:null,selectedFruit:null,hidden:false});
        }
      });
    return true;
  },
  showLevelTwoFruits(data){
    var str='<div id="delEle" style="height:auto;max-height:12.5rem;padding:0 1rem;overflow-y:scroll;background-color: #f0f0f0;opacity:0.7">';
    if(data){
      $.each(data,function(idx,item){
        str+='<span id="'+item.code+'">'+item.name+'</span>';
      });
    }
    str+='</div>';
    return str;
  },
  getFruitsItemList(node,html){
    var _self=this;
    node.innerHTML='';
    //拿到二级分类下的所有果品后，需要拼接进二级分类的Li下面，拼接之前需要先清空
    var el = document.getElementById('delEle');
    if(el){
      el.parentNode.removeChild(el);
    }
    node.innerHTML += html+this.state.fruitsItemList;
    //拼接完成后需要为每个单品添加点击事件
    var ele = document.getElementById('delEle');
    ele.addEventListener('click',function(e){
      _self.setState({
        value:e.target.innerHTML,
        goodsCode:e.target.id,
        fruitsItemList:''
      });
      //跳转回发布页面，并带回水果信息
      var innerHTML = e.target.innerHTML;
      var innerCode = e.target.id;
      window.sessionStorage.setItem('goodsName', JSON.stringify(innerHTML));
      window.sessionStorage.setItem('goodsCode', JSON.stringify(innerCode));

      const path = 'publishFruit';
      hashHistory.push(path);
    });

  },
  selCurrentFruit(e){
    this.setState({
      value:e.target.innerHTML,
      goodsCode:e.target.id
    });
    //跳转回发布页面，并带回水果信息
    var innerHTML = e.target.innerHTML;
    var innerCode = e.target.id;
    window.sessionStorage.setItem('goodsName', JSON.stringify(innerHTML));
    window.sessionStorage.setItem('goodsCode', JSON.stringify(innerCode));
    const path = 'publishFruit';
    hashHistory.push(path);
  },
  handleBack(){
    window.history.back();
  },
    render:function(){
      var selCateItem = this.selCateItem;
      var selLevelOne = this.selLevelOne;
      var selCurrentFruit = this.selCurrentFruit;
        var tips = [];
        var levelOne = [];
        var keyList = [];
      if(this.state.showCateList){
        if(this.state.cateFruits != null && this.state.cateFruits.length != 0){
          var items = [];
          $.each(this.state.cateFruits,function(idx,item){
            items.push(<li id={item.code} key={item.code} onClick={selCateItem}>{item.name}</li>);
          });
          tips = <ul>{items}</ul>
        }else{
          tips = <div style={{'width':'100%','textAlign':'center'}}>暂无水果品类</div>
        }
      }else if(this.state.showLevelOne){
        if(this.state.LevelOneFruits != null && this.state.LevelOneFruits.length != 0){
          var items = [];
          $.each(this.state.LevelOneFruits,function(idx,item){
            items.push(<li id={item.code} key={item.code} onClick={selLevelOne}>{item.name}<span className='icon-more'></span></li>);
          });
          levelOne = <ul>{items}</ul>
        }else{
          levelOne = <div style={{'width':'100%','textAlign':'center'}}>暂无水果品类</div>
        }
      }else if(this.state.showKeyList){
        if(this.state.candidateFruits != null && this.state.candidateFruits.length != 0){
          var items = [];
          $.each(this.state.candidateFruits,function(idx,item){
            items.push(<li id={item.code} key={item.code} onClick={selCurrentFruit}>{item.name}</li>);
          });
          keyList = <ul>{items}</ul>
        }else{
          keyList = <div style={{'width':'100%','textAlign':'center'}}>暂无水果</div>
        }
      }

        return (
          <article className='sel-fruit-box'>
            <HeadTitleComponent title={this.state.title} handleBack={this.handleBack}/>
            <article style={{'marginTop':'5.3rem'}}>
                <div className='sel-item'>
                  <input value={this.state.value} onChange={this.handleFruitInput} onFocus={this.handleFocus} onBlur={this.handleLeaveInput} ref='inputedFruit'></input>
                  <label>搜索</label>
                </div>
            </article>
            <article  style={{'marginTop':'5.3rem'}} className={this.state.showCateList?'fruit-detail':'fruit-detail sink'}>
              <div className='sel-cate-box'>
                {tips}
              </div>
            </article>
            <article  style={{'marginTop':'5.3rem'}} className={this.state.showLevelOne?'fruit-detail':'fruit-detail sink'}>
              <div className='sel-level-one' id='levelOne'>
                {levelOne}
              </div>
            </article>
            <article  style={{'marginTop':'5.3rem'}} className={this.state.showKeyList?'fruit-detail':'fruit-detail sink'}>
              <div className='sel-key-fruits'>
                {keyList}
              </div>
            </article>
          </article>
        );
    }
});

return _FruitSelectionPage;
});
